<?php
namespace app\common\service;

use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Payout;
use PayPal\Api\Payment;
use PayPal\Api\Payer;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\PaymentExecution;
use think\Config;

class PayPalService
{
    protected $apiContext;
    
    public function __construct()
    {
        $config = Config::get('paypal');

        // dump($config); exit;
        
        $this->apiContext = new ApiContext(
            new OAuthTokenCredential(
                $config['client_id'],
                $config['client_secret']
            )
        );
        
        $this->apiContext->setConfig([
            'mode' => $config['mode'],
            'log.LogEnabled' => true,
            'log.FileName' => RUNTIME_PATH . 'log/paypal.log',
            'log.LogLevel' => 'INFO'
        ]);
    }
    
    /**
     * 创建支付
     * @param float $amount 金额
     * @param string $currency 货币类型
     * @param string $description 描述
     * @return array
     */
    public function createPayment($amount, $currency = 'USD', $description = '')
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');
        
        $amountObj = new Amount();
        $amountObj->setTotal($amount)
                  ->setCurrency($currency);
        
        $transaction = new Transaction();
        $transaction->setAmount($amountObj)
                    ->setDescription($description);
        
        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl(Config::get('paypal.return_url'))
                     ->setCancelUrl(Config::get('paypal.cancel_url'));
        
        $payment = new Payment();
        $payment->setIntent('sale')
                ->setPayer($payer)
                ->setTransactions([$transaction])
                ->setRedirectUrls($redirectUrls);
        
        try {
            $payment->create($this->apiContext);
            // 获取跳转地址
            foreach ($payment->getLinks() as $link) {
                if ($link->getRel() == 'approval_url') {
                    $approvalUrl = $link->getHref();
                    break;
                }
            }
            
            return [
                'success' => true,
                'approval_url' => $approvalUrl,
                'payment_id' => $payment->getId()
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 执行支付
     * @param string $paymentId
     * @param string $PayerID
     * @return array
     */
    public function executePayment($paymentId, $PayerID)
    {
        try {
            $payment = Payment::get($paymentId, $this->apiContext);
            $execution = new PaymentExecution();
            $execution->setPayerId($PayerID);
            
            $result = $payment->execute($execution, $this->apiContext);
            
            return [
                'success' => true,
                'data' => $result
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 查询支付状态
     * @param string $paymentId
     * @return array
     */
    public function getPaymentStatus($paymentId)
    {
        try {
            $payment = Payment::get($paymentId, $this->apiContext);
            return [
                'success' => true,
                'status' => $payment->getState(),
                'data' => $payment
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}
